package com.cug.campus_sh_market_server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cug.campus_sh_market_server.config.aop.ValidateAspect;
import com.cug.campus_sh_market_server.entity.myenum.UserTypeEnum;
import com.cug.campus_sh_market_server.entity.param.OrderParam;
import com.cug.campus_sh_market_server.entity.param.PageParam;
import com.cug.campus_sh_market_server.entity.param.user.*;
import com.cug.campus_sh_market_server.entity.po.User;
import com.cug.campus_sh_market_server.entity.vo.ResultData;
import com.cug.campus_sh_market_server.entity.vo.user.UserTypeVO;
import com.cug.campus_sh_market_server.entity.vo.user.UserVO;
import com.cug.campus_sh_market_server.service.UserService;
import com.cug.campus_sh_market_server.util.MD5Util;
import com.cug.campus_sh_market_server.util.UUIDUtils;
import com.cug.campus_sh_market_server.util.UserContext;
import com.nycreativity.elecreativity.entity.vo.PageDataVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import static com.cug.campus_sh_market_server.common.constant.UrlConstants.USER_PREFIX;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-04-26
 */
@RestController
@RequestMapping(USER_PREFIX)
@Slf4j
@Api(tags = "用户相关")
public class UserController extends AbsPreAuthorizeRestfullController
        <User, UserQueryParam, UserAddParam, UserUpdateParam, UserVO> {

    @Resource
    private UserService userService;

    @PreAuthorize("permitAll()")
    @ApiOperation(value = "新增用户信息记录")
    @ValidateAspect.ParamValidate()
    public ResultData<UserVO> addData(
            @RequestBody @Valid UserAddParam userAddParam,
            @ApiParam(hidden = true) @SuppressWarnings("unused") BindingResult bindingResult) {

        //账号重复性判断
        int count = userService.count(new LambdaQueryWrapper<User>().eq(User::getAccount, userAddParam.getAccount()));
        if (count > 0) {
            log.info("用户信息添加失败, 账号信息已存在");
            return ResultData.FAILED("用户信息添加失败, 账号信息已存在", null);
        }

        //添加操作
        UserVO save = restfullService.saveWithBackData(userAddParam);

        //结果返回
        if (save != null) {
            log.info("用户信息添加成功");

            return ResultData.SUCCESS("用户信息添加成功", save);
        } else {
            log.info("用户信息添加失败");
            return ResultData.FAILED("用户信息添加失败", null);
        }

    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN','SUPER_ADMIN', 'ROLE_USER')")
    @ApiOperation(value = "查询用户信息(传入条件则根据条件查询, 否则查询全部数据)")
    @Override
    protected ResultData<PageDataVO<UserVO>> getDataByPage(UserQueryParam userQueryParam, PageParam pageParam, OrderParam orderParam) {
        return super.getDataByPage(userQueryParam, pageParam, orderParam);
    }

    @GetMapping("{id}")
    @ApiOperation(value = "根据用户id查询用户信息")
    public ResultData<UserVO> getUserById(@PathVariable Integer id) {
        log.info("根据用户id查询用户信息");
        return ResultData.SUCCESS("成功", userService.queryUsersById(id));
    }

    @GetMapping("/type/{account}")
    @ApiOperation(value = "根据账号用户类型")
    public ResultData<UserTypeVO> getUserType(@PathVariable String account) {
        log.info("根据账号获取用户类型");
        User user = userService.queryUserByAccount(account);
        if (ObjectUtils.isEmpty(user)) {
            return ResultData.FAILED("账号错误");
        }
        UserTypeVO userTypeVO = new UserTypeVO();
        userTypeVO.setTypeCode(user.getUserType());
        userTypeVO.setType(UserTypeEnum.getTypeByCode(user.getUserType()));
        return ResultData.SUCCESS("成功", userTypeVO);
    }


    @GetMapping("/current")
    @ApiOperation(value = "获取当前用户信息")
    public ResultData<UserVO> getCurrentUsers() {
        log.info("查询当前用户信息");
        return ResultData.SUCCESS("成功", userService.queryById(UserContext.get().getId()));
    }

    @PutMapping("changeUserStatus")
    @ApiOperation(value = "修改用户状态")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','SUPER_ADMIN')")
    public ResultData<Object> changeUserStatus(@RequestBody UserStatusUpdateParam userStatusUpdateParam) {
        User user = userService.getById(userStatusUpdateParam.getId());
        if (user != null) {
            user.setActive(userStatusUpdateParam.getActive());
            user.modify();
            boolean rs = userService.updateById(user);
            return rs ? ResultData.SUCCESS("操作成功") : ResultData.FAILED("操作失败");
        }
        return ResultData.FAILED("操作失败");
    }

    @PutMapping("resetPassword")
    @ApiOperation(value = "重置用户密码")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','SUPER_ADMIN', 'ROLE_USER')")
    public ResultData<Object> resetPassword(@RequestBody UserRestPasswordParam passwordParam) {
        boolean rs = userService.resetPassword(passwordParam);
        return rs ? ResultData.SUCCESS("操作成功") : ResultData.FAILED("操作失败");
    }

    /*=========================================华丽的分割线==============================================*/

    /**
     * 访问禁止需要授权提示信息
     *
     * @return 访问禁止需要授权提示信息
     */
    @PreAuthorize("permitAll()")
    @ApiOperation(value = "访问禁止需要授权提示信息", hidden = true)
    @RequestMapping("/authentication/require")
    public ResultData<Boolean> requireAuthentication() {
        log.info("需要登录");
        return ResultData.AUTH_FAILED();
    }


}

